// miniprogram/pages/idx/idx.js
const viewIds = ['a', 'b', 'c', 'd', 'e'];
const app = getApp()

// 引入SDK核心类
const QQMapWX = require('../../lib/qqmap-wx-jssdk');

// 实例化API核心类
const qqmapsdk = new QQMapWX({
  key: 'AGTBZ-CU2KP-DIMDL-L32KL-POWNE-NDF5U' // 必填
});

// m
let isMoving = false;
let mapControlClick = false;
Page({
  data: { // data
    userInfo: {},
    tabId: '0',
    tabs: [{
        _id: '0',
        name: '指标A',
      },
      {
        _id: '1',
        name: '指标B',
      },
      {
        _id: '2',
        name: '指标C',
      },
      {
        _id: '3',
        name: '指标D',
      },
      {
        _id: '4',
        name: '指标E',
      },
    ],
    subtabId: '0',
    subtabs: [{
        _id: '0',
        name: '指标A-0',
        pid: '0'
      },
      {
        _id: '1',
        name: '指标A-1',
        pid: '0'
      },
      {
        _id: '2',
        name: '指标A-2',
        pid: '0'
      },
      {
        _id: '3',
        name: '指标A-3',
        pid: '0'
      },
      {
        _id: '4',
        name: '指标A-4',
        pid: '0'
      },
    ],
    reftabId: '0',
    reftabs: [{
        _id: '0',
        name: '公园',
        active: true,
      },
      {
        _id: '1',
        name: '后工业',
        active: false,
      },
    ],
    scale: 18,
    latitude: 0,
    longitude: 0,
    // markers: [{
    //   iconPath: "/images/position.png",
    //   id: 0,
    //   latitude: 23.099994,
    //   longitude: 113.324520,
    //   width: 30,
    //   height: 30
    // }],
    oriMarkers: [],
    markers: [],
    polygon: [
      // {
      //   points: [
      //     {
      //       longitude: 116.41219,
      //       latitude: 39.905244,
      //     },
      //     {
      //       longitude: 116.41033,
      //       latitude: 39.910027,
      //     },
      //     {
      //       longitude: 116.403304,
      //       latitude: 39.908097,
      //     },
      //   ],
      //   strokeColor: "#FF0000DD",
      //   strokeWidth: 2,
      //   fillColor: "#FF0000DD",
      //   zIndex: 1000
      // },
    ],
    formFlag: false,
    cmtval: '',
    markObj: { // 提交所需参数id
      reftabId: '0',
      tabId: '0',
      subtabId: '',
      lat: 0,
      lng: 0,
      title: '',
      adr: '',
      cmts: [],
    },
    markFlag: false,
    popShow: '', // form框 是否弹出
  },
  onLoad(options) { // 监听页面加载
    // loading
    wx.showLoading({
      title: '',
      mask: true,
    });

    // 获取用户信息
    wx.getSetting({
      success: res => {
        // loaded
        wx.hideLoading();
        // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: res => {
              const userInfo = {
                nickName: res.userInfo.nickName,
                avatarUrl: res.userInfo.avatarUrl,
                detail: res.userInfo
              };
              app.globalData.userInfo = userInfo;
              this.setData({
                userInfo,
              });
            },
          });
        }
      },
    });
    // 获取用户当前位置
    wx.getLocation({
      success: (res) => {
        console.log(res)
        const {
          latitude,
          longitude
        } = res;
        this.setData({
          longitude,
          latitude,
        })
      },
    });
    // 获取所有标记点
    this.markGetall();
  },
  onGetUserInfo(res) { // 登录成功的回调
    if (res.detail.userInfo) {
      const userInfo = {
        nickName: res.userInfo.avatarUrl,
        avatarUrl: res.userInfo.avatarUrl,
        detail: res.userInfo
      };
      app.globalData.userInfo = userInfo;
      this.setData({
        userInfo,
      });
    } else {
      wx.showToast({
        title: '网络异常，请稍后重试',
      });
    }
  },
  tabChange(e) { // 顶部tabs点击切换
    const tabId = e.target.dataset.id;
    const markObj = this.data.markObj;
    markObj.tabId = tabId;
    this.setData({
      tabId,
      markObj,
    });
  },
  subtabChange(e) { // 顶部subtabs点击切换
    const subtabId = e.target.dataset.id;
    const markObj = this.data.markObj;
    markObj.subtabId = subtabId;
    this.setData({
      subtabId,
      markObj,
    });
  },
  reftabChange(e) { // 低部tabs点击切换
    const i = e.target.dataset.index
    const reftabs = this.data.reftabs.map((item, idx) => ({
      ...item,
      active: i === idx
    }));
    this.setData({
      reftabs,
    })
  },
  regionchange(e) { // 地图视野变化
    console.log('视野：', e.type);
    if (e.type === 'begin') {
      return false;
    }
    let that = this;
    console.log('视野发生变化时触发===', that)
    that.mpCtx = wx.createMapContext('map');
    that.mpCtx.getScale({ //获取当前地图的缩放级别
      success: (res) => {
        console.log('地图缩放级别', res.scale)
        that.mpCtx.getCenterLocation({ //获取当前地图中心的经纬度。返回的是 gcj02 坐标系
          success: (res) => {
            console.log('获取center中心数据', res);
            qqmapsdk.reverseGeocoder({ //逆地址解析
              location: {
                latitude: res.latitude,
                longitude: res.longitude,
              },
              success: (res1) => {
                let res = res1.result
                console.log('逆地址解析res===', res);
                const location = {
                  lat: res.location.lat,
                  lng: res.location.lng,
                  adr: res.address,
                  title: res.formatted_addresses.recommend,
                };
                const markObj = this.data.markObj;
                that.setData({
                  markObj: { ...markObj,
                    ...location
                  },
                  markFlag: true,
                });
              }
            })
          }
        })
      },
      fail: function() {
        console.log('获取当前地图的缩放级别失败===')
      }
    })
  },
  showCmtbox() { // 显示评论信息框
    this.setData({
      popShow: 'show',
    });
  },
  hideCmtbox() { // 隐藏评论信息框
    this.setData({
      popShow: 'hide',
    });
  },
  markertap(e) { // 点击marker
    console.log(e);
    console.log(this.data.oriMarkers);
    isMoving = true;
    const marker = this.data.oriMarkers.find(item => item._id === e.markerId);
    this.setData({
      tabId: marker.tabId,
      subtabId: marker.subtabId,
      curSubtabId: marker.subtabId,
      reftabId: marker.reftabId,
      markFlag: true,
      markObj: marker,
      latitude: marker.lat,
      longitude: marker.lng,
    });

    this.polygonGetone(e.markerId);
  },
  controltapAdd() { // 点击control
    mapControlClick = true;
    let scale = this.data.scale;
    if (scale > 19) {
      return false;
    } else {
      scale++;
    }
    console.log(scale);
    this.setData({
      scale,
    });
  },
  controltapCut() { // 点击control
    mapControlClick = true;
    let scale = this.data.scale;
    if (scale < 4) {
      return false;
    } else {
      scale--;
    }
    this.setData({
      scale,
    });
  },
  maptap(e) { // 点击地图空白处
    if (!this.data.markObj.subtabId || !this.data.markFlag) {
      return false;
    }
    console.log(e);
    this.setData({
      markFlag: false,
    });
  },
  markSubmit(e) { // 提交评论 新增还是修改
    if (this.data.markObj._id) {
      this.markEditone(e);
    } else {
      this.markAddone(e);
    }
  },
  markAddone(e) { // 提交 mark
    const comment = e.detail.value.textarea.replace(/\s/, '');
    const markObj = this.data.markObj;
    const {
      nickName,
      avatarUrl
    } = app.globalData.userInfo;
    const data = {
      ...markObj,
    };
    if (comment) {
      data.cmts = [{
        nickName,
        avatarUrl,
        comment,
      }];
    }
    // 调用
    wx.cloud.callFunction({
      name: 'marker',
      data: {
        data,
        type: 'addone'
      },
      success: res => {
        console.log('[云函数] [mark]:', res);
        const _id = res.result._id;
        data._id = _id;
        // 成功 赋值
        const oriMarkers = this.data.oriMarkers;
        const markers = this.data.markers;
        oriMarkers.push(data);
        markers.push({
          iconPath: "/images/position.png",
          id: _id,
          latitude: data.lat,
          longitude: data.lng,
          width: 30,
          height: 30,
        })
        this.setData({
          oriMarkers,
          markers,
          markFlag: false,
          cmtval: '',
          subtabId: '',
        });
      },
      fail: err => {
        console.error('[云函数] [mark]:', err)
      }
    })
  },
  markGetall() { // 获取 所有 mark
    // 调用
    wx.cloud.callFunction({
      name: 'marker',
      data: {
        type: 'getall'
      },
      success: res => {
        console.log('[云函数] [mark]:', res);
        const result = res.result.data;
        this.setData({
          oriMarkers: result,
        }, () => {
          const markers = result.map(item => ({
            iconPath: "/images/position.png",
            id: item._id,
            latitude: item.lat,
            longitude: item.lng,
            width: 30,
            height: 30
          }));
          this.setData({
            markers,
          });
        });
      },
      fail: err => {
        console.error('[云函数] [mark]:', err)
      }
    })
  },
  markEditone(e) { // 更新 mark -- 评论
    const comment = e.detail.value.textarea.replace(/\s/, '');
    const {
      _id
    } = this.data.markObj;
    const {
      nickName,
      avatarUrl
    } = app.globalData.userInfo;
    console.log(_id);
    const data = {
      _id,
    };
    if (comment) {
      data.cmt = {
        nickName,
        avatarUrl,
        comment,
      };
    } else {
      wx.showToast({
        title: '请先输入评论',
        icon: 'none',
      });
      return false;
    }
    // 调用
    wx.cloud.callFunction({
      name: 'marker',
      data: {
        data,
        type: 'editone'
      },
      success: res => {
        const result = this.data.oriMarkers;
        for (let i = 0; i < result.length; i++) {
          if (result[i]._id === _id) {
            result[i].cmts.unshift(data.cmt);
            break;
          }
        }
        const markers = result.map(item => ({
          iconPath: "/images/position.png",
          id: item._id,
          latitude: item.lat,
          longitude: item.lng,
          width: 30,
          height: 30,
        }));
        this.setData({
          oriMarkers: result,
          markers,
          markFlag: false,
          cmtval: '',
          subtabId: '',
        });
      },
      fail: err => {
        console.error('[云函数] [mark]:', err)
      }
    })
  },
  markGetone() { // 获取 所有 mark
    // 调用
    wx.cloud.callFunction({
      name: 'marker',
      data: {
        type: 'getone'
      },
      success: res => {
        console.log('[云函数] [mark]:', res);
        const markers = res.result.data.map(item => ({
          iconPath: "/images/position.png",
          id: item._id,
          latitude: item.lat,
          longitude: item.lng,
          width: 30,
          height: 30
        }));
        this.setData({
          markers,
        });
      },
      fail: err => {
        console.error('[云函数] [mark]:', err)
      }
    })
  },
  polygonAddone() {
    const data = {
      _id: 'f885cb355d87513102a781c64378b19c',
      polygon: {
        points: [{
            longitude: 116.41219,
            latitude: 39.905244,
          },
          {
            longitude: 116.41033,
            latitude: 39.910027,
          },
          {
            longitude: 116.403304,
            latitude: 39.908097,
          },
        ],
        strokeColor: "#FF0000DD",
        strokeWidth: 2,
        fillColor: "#FF0000DD",
        zIndex: 1000,
      },
    };
    // 调用
    wx.cloud.callFunction({
      name: 'polygon',
      data: {
        data,
        type: 'addone'
      },
      success: res => {
        console.log('[云函数] [polygon]:', res);
      },
      fail: err => {
        console.error('[云函数] [polygon]:', err)
      }
    })
  },
  polygonGetone(_id) {
    // 调用
    wx.cloud.callFunction({
      name: 'polygon',
      data: {
        data: {
          _id
        },
        type: 'getone'
      },
      success: res => {
        console.log('[云函数] [polygon]:', res.result.data.polygon);
        const polygon = [res.result.data.polygon] || [];
        this.setData({
          polygon,
        });
      },
      fail: err => {
        console.error('[云函数] [polygon]:', err)
      }
    })
  }
})